/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.client.sec.content.role;

import han.bifang.gwt.client.common.Content;
import han.bifang.gwt.client.common.GwtContext;
import han.bifang.gwt.client.common.PrivilegChecker;
import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.common.entity.Resource;
import han.bifang.gwt.client.common.entity.Usergroup;
import han.bifang.gwt.client.common.util.StringUtils;
import han.bifang.gwt.client.communicate.BifangGWTServiceAsync;
import han.bifang.gwt.client.sec.CustomCheckBox;
import han.bifang.gwt.client.sec.SecurityMessages;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;

/**
 * 
 * @Author Kent
 */
public class RoleGroupRelContent extends Content implements
		GroupAndResourceSearcher {

	private SecurityMessages cons = null;

	private BifangGWTServiceAsync service = null;

	private GwtContext context = null;
	private VerticalPanel panel;

	private String roleId;

	private SimplePanel tablePanel;
	private CustomCheckBox[] checks;
	private ArrayList<Usergroup> g, tmp;

	private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			for (CustomCheckBox check : checks) {
				if (check.isChecked()) {
					Usergroup gr = (Usergroup) check.getProperties();
					g.remove(gr);
				}
			}
			refreshTable(g);

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	private AsyncCallback<ResponseObject> cb1 = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			g.addAll(tmp);
			tmp = null;
			refreshTable(g);

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	public RoleGroupRelContent(SecurityMessages cons,
			BifangGWTServiceAsync service, GwtContext context, String id,
			ArrayList<Usergroup> g) {
		this.service = service;
		this.context = context;
		this.cons = cons;
		this.roleId = id;
		this.g = g;
		if (g == null) {
			g = new ArrayList<Usergroup>();
		}

		panel = new VerticalPanel();
		panel.setSpacing(5);
		panel.setWidth("100%");

		tablePanel = new SimplePanel();
		tablePanel.setWidth("100%");
		panel.add(tablePanel);

		initWidget(panel);

	}

	public void onLoad() {
		refreshTable(g);

		HorizontalPanel h = new HorizontalPanel();
		Button b = new Button(cons.addGroup(), new ClickListener() {
			public void onClick(Widget sender) {
				DialogBox dialogBox = createDialogBox();
				dialogBox.setText(cons.addGroup());
				dialogBox.center();
				dialogBox.show();
			}
		});

		Button b1 = new Button(cons.removeGroup());
		b1.addClickListener(new ClickListener() {

			public void onClick(Widget sender) {
				RequestObject req = new RequestObject();
				req
						.setAction("han.bifang.gwt.server.action.sec.role.RemoveGroupsOfRoleAction");
				ArrayList<String> param = new ArrayList<String>();
				param.add(roleId);

				for (CustomCheckBox check : checks) {
					if (check.isChecked()) {
						Usergroup gr = (Usergroup) check.getProperties();
						param.add(gr.getId());
					}
				}

				req.setRequest(param);
				service.call(req, cb);

			}

		});

		h.add(b);
		h.add(new HTML("&nbsp;&nbsp;"));
		h.add(b1);

		panel.add(new HTML("&nbsp;"));
		if (PrivilegChecker.hasPrivilege(context, null))
			panel.add(h);

	}

	private void refreshTable(List<Usergroup> g) {
		FlexTable table = new FlexTable();
		table.setWidth("60%");
		table.setCellPadding(1);
		table.setCellSpacing(1);
		table.setBorderWidth(1);

		ColumnFormatter cf = table.getColumnFormatter();
		cf.setWidth(0, "10%");
		cf.setWidth(1, "30%");
		cf.setWidth(2, "60%");

		CellFormatter ff = table.getCellFormatter();
		ff.setStyleName(0, 0, "tablecol");
		ff.setStyleName(0, 1, "tablecol");
		ff.setStyleName(0, 2, "tablecol");

		table.setHTML(0, 0, "&nbsp;");
		table.setHTML(0, 1, cons.groupName());
		table.setHTML(0, 2, cons.description());

		checks = new CustomCheckBox[g.size()];
		for (int i = 0, j = g.size(); i < j; i++) {
			int row = table.getRowCount();
			table.insertRow(row);
			checks[i] = new CustomCheckBox();
			checks[i].setProperties(g.get(i));
			table.setWidget(row, 0, checks[i]);
			table.setHTML(row, 1, g.get(i).getGroupName());
			table.setHTML(row, 2, StringUtils
					.isEmpty(g.get(i).getDescription()) ? "&nbsp;" : g.get(i)
					.getDescription());

		}
		tablePanel.setWidget(table);
	}

	private DialogBox createDialogBox() {
		DialogBox dialogBox = new DialogBox();
		dialogBox.setWidth("50%");
		SearchGroupPanel gp = new SearchGroupPanel(cons, service, roleId,
				dialogBox, g);
		gp.setSearcher(this);
		dialogBox.setWidget(gp);

		return dialogBox;
	}

	public void onGroupResult(ArrayList<Usergroup> g1) {
		tmp = g1;

		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.sec.role.AddGroupsOfRoleAction");
		ArrayList<String> param = new ArrayList<String>();
		param.add(roleId);

		for (Usergroup gg : g1) {

			param.add(gg.getId());

		}

		req.setRequest(param);
		service.call(req, cb1);

	}

	public void onResourceResult(ArrayList<Resource> r) {
		// TODO Auto-generated method stub

	}

}
